<template>
    <!-- pages/site/addsite/index.wxml -->
    <view class="pages">
        <view class="box">
            <view class="h-86 centers">
                <view class="text1">收货人</view>
                <input type="text" @input="inputEdit" placeholder="名字" :value="name" placeholder-class="placeholder-class" data-name="name" />
            </view>
            <view class="h-86 centers">
                <view class="text1">手机号码</view>
                <input type="number" placeholder="手机号" @input="inputEdit" :value="phone" placeholder-class="placeholder-class" data-name="phone" />
            </view>
            <view class="h-86 flexbox-sb">
                <view class="centers">
                    <view class="text1">所在地区</view>
                    <view class="placeholder-class" @tap="showmolde">{{ city }}</view>
                </view>
                <view @tap="getUserLocation" class="centers">
                    <van-icon name="location-o" color="#FF8722" />
                </view>
            </view>
            <view class="centers detail">
                <view class="text1">详细地址</view>
                <textarea
                    class="textarea"
                    type="text"
                    @input="inputEdit"
                    :value="detailAddress"
                    placeholder="小区楼栋/乡村名称"
                    placeholder-class="textarea-placeholder"
                    data-name="detailAddress"
                ></textarea>
            </view>
        </view>
        <view class="centers mt-20" @tap="setDefault" :data-id="item.id">
            <view :class="'iconbox centers mr-10 ' + (bool ? 'iconbox1' : '')">
                <image class="icon-24" v-if="bool" :src="imgUrl + 'step33.png'"></image>
            </view>
            <text class="site-text2">默认地址</text>
        </view>
        <view class="addbtn" @tap="onAdd" v-if="type == 'add'">保存</view>
        <view class="addbtn" @tap="edit" v-if="type == 'edit'">修改</view>
        <van-popup :show="show" position="bottom" @close="onClose">
            <van-area :area-list="areaList" :columns-num="3" title="选择城市" @cancel="onClose" @confirm="onFirm" />
        </van-popup>
    </view>
</template>

<script>
// pages/site/addsite/index.js
const app = getApp(); // 引入app

import _request from '../../../utils/request.js'; // 引入SDK核心类，js文件根据自己业务，位置可自行放置

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');

var qqmapsdk;

const area = require('../../../utils/area');

export default {
    data() {
        return {
            type: 'add',
            dataEdit: {},
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            bool: false,

            city: '省、市、区',
            show: false,
            name: null,
            phone: null,
            detailAddress: null,
            areaList: area.areaList,
            markers: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.setData({
            type: options.type
        });

        if (options.data) {
            uni.setNavigationBarTitle({
                title: '修改地址'
            });
            let dataEdit = JSON.parse(options.data);
            this.setData({
                dataEdit: dataEdit,
                name: dataEdit.name,
                phone: dataEdit.phone,
                detailAddress: dataEdit.detailAddress,
                bool: Boolean(dataEdit.receiveStatus),
                city: [dataEdit.province, dataEdit.city, dataEdit.region]
            });
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (e) {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 展示选择城市
        showmolde() {
            this.setData({
                show: true
            });
        },

        // 关闭选择城市
        onClose() {
            this.setData({
                show: false
            });
        },

        // 完成选择城市，发送请求
        onFirm(e) {
            this.setData({
                show: false,
                city: e.detail.values.map((item) => {
                    return item.name;
                })
            });
        },

        inputEdit(e) {
            let name = e.currentTarget.dataset.name;
            this[name] = e.detail.value;
        },

        edit() {
            _request
                .postObj(
                    '/receiveAndDeliver/updateReceiveAndDeliverAddressById',
                    {
                        userId: uni.getStorageSync('userId'),
                        id: this.dataEdit.id,
                        receiveStatus: Number(this.bool),
                        name: this.name,
                        phone: this.phone,
                        detailAddress: this.detailAddress,
                        province: this.city[0],
                        city: this.city[1],
                        region: this.city[2],
                        regionalCode: '0'
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        uni.navigateBack({
                            url: '/pages/site/index'
                        });
                    }
                });
        },

        onAdd() {
            ///receiveAndDeliver/saveReceiveAndDeliverAddress
            _request
                .postObj(
                    '/receiveAndDeliver/saveReceiveAndDeliverAddress',
                    {
                        userId: uni.getStorageSync('userId'),
                        receiveStatus: Number(this.bool),
                        name: this.name,
                        phone: this.phone,
                        detailAddress: this.detailAddress,
                        province: this.city[0],
                        city: this.city[1],
                        region: this.city[2],
                        regionalCode: '0'
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        uni.navigateBack({
                            url: 'pages/site/index'
                        });
                    }
                });
        },

        //设置默认
        setDefault() {
            this.setData({
                bool: !this.bool
            });
        },

        // 获取用户定位
        getUserLocation() {
            let vm = this;
            uni.getSetting({
                success(res) {
                    // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
                    // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
                    // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
                    if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                        uni.showModal({
                            title: '请求授权当前位置',
                            content: '需要获取您的地理位置，请确认授权',
                            success: function (res) {
                                if (res.cancel) {
                                    uni.showToast({
                                        title: '拒绝授权',
                                        icon: 'none',
                                        duration: 2000
                                    });
                                } else if (res.confirm) {
                                    uni.openSetting({
                                        success: function (dataAu) {
                                            if (dataAu.authSetting['scope.userLocation'] == true) {
                                                uni.showToast({
                                                    title: '授权成功',
                                                    icon: 'success',
                                                    duration: 2000
                                                }); //再次授权，调用wx.getLocation的API

                                                vm.getLocation();
                                            } else {
                                                uni.showToast({
                                                    title: '授权失败',
                                                    icon: 'none',
                                                    duration: 2000
                                                });
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    } else if (res.authSetting['scope.userLocation'] == undefined) {
                        // 不存在就获取权限
                        vm.getLocation();
                    } else {
                        //调用wx.getLocation的API
                        vm.getLocation();
                    }
                }
            });
        },

        // 授权定位权限
        getLocation() {
            var _this = this;

            uni.getLocation({
                type: 'wgs84',
                success: function (res) {
                    let latitude = res.latitude;
                    let longitude = res.longitude; // 实例化API核心类

                    qqmapsdk = new QQMapWX({
                        key: 'MBEBZ-6VQCP-EYSDK-LT7FQ-2LNUS-G4BTN'
                    }); // 经纬度转城市

                    qqmapsdk.reverseGeocoder({
                        //位置坐标
                        location: {
                            latitude: latitude,
                            longitude: longitude
                        },
                        //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
                        success: function (res) {
                            //成功后的回调
                            var res = res.result;
                            var mks = [];
                            mks.push({
                                // 获取返回结果，放到mks数组中
                                title: res.address,
                                id: 0,
                                latitude: res.location.lat,
                                longitude: res.location.lng,
                                iconPath: '/static/pages/site/addsite/resources/placeholder.png',
                                //图标路径
                                width: 20,
                                height: 20,
                                callout: {
                                    //在markers上展示地址名称，根据需求是否需要
                                    content: res.address,
                                    color: '#000',
                                    display: 'ALWAYS'
                                },
                                ad_info: res.ad_info,
                                address_component: res.address_component
                            });

                            _this.setData({
                                //设置markers属性和地图位置poi，将结果在地图展示
                                markers: mks,
                                city: res.ad_info.province + ',' + res.ad_info.city + ',' + res.ad_info.district
                            });
                        },
                        fail: function (error) {
                            console.error(error);
                        },
                        complete: function (res) {}
                    }); // 储存地址

                    uni.setStorageSync('location', res);
                },
                fail: function (error) {
                    console.log(error, 'error');
                }
            });
        }
    }
};
</script>
<style>
/* pages/site/addsite/index.wxss */
.pages {
    padding: 0 20rpx;
}

.box {
    width: 710rpx;
    height: 384rpx;
    background: #ffffff;
    box-shadow: 0px 1px 29px 0px rgba(0, 0, 0, 0.04);
    border-radius: 10rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
}

.h-86 {
    height: 86rpx;
    width: 100%;
    border-bottom: 1px solid #e8e8e8;
}

.text1 {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    width: 140rpx;
}

.detail {
    padding-top: 20rpx;
}

.detail > .text1 {
    position: relative;
    top: -38rpx;
}
input {
    font-size: 28rpx;
}
.textarea {
    height: 100rpx;
    width: 500rpx;
    font-size: 28rpx;
}

.textarea-placeholder {
    font-size: 24rpx;
    color: #999999;
}

.placeholder-class {
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #000;
}

.site-text2 {
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #666666;
    line-height: 36rpx;
}

.iconbox {
    width: 24rpx;
    height: 24rpx;
    border: 1px solid #999999;
    border-radius: 50%;
}

.iconbox1 {
    border: 1px solid #ff8722;
}

.addbtn {
    width: 690rpx;
    height: 90rpx;
    background: #ff8722;
    border-radius: 45rpx;
    font-size: 36rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #f3f3f3;
    line-height: 90rpx;
    text-align: center;
    margin: 30rpx;
}
</style>
